<template>
  <basePage ref="basePage">
    <view class="order-payment-con">
      <address-bar :order-detail-data="curOrderDetailData" />
      <view class="list-sku list-bg">
        <view class="company">{{ curOrderDetailData.branchName }}</view>
        <view class="editor-box">
          <text v-if="!editorStatus && curOrderDetailData.orderStatus==10" class="font-size-color" @click="editFn">编辑</text>
          <text v-if="editorStatus && curOrderDetailData.orderStatus==10" class="font-size-color" @click="cancelEditFn">取消</text>
          <text v-if="editorStatus && curOrderDetailData.orderStatus==10" class="font-size-color" @click="completeFn">完成</text>
        </view>
        <OrderProductItem
          :editor-status="editorStatus"
          :order-items-detail-data.sync="curOrderProductList"
          :total-record="totalRecord"
          :order-detail-data="curOrderDetailData"
          :show-warehouse-label="showWarehouseLabel"
          :all-goods-page-path="'/goodsPages/orderAllgoods'"
        />
      </view>
      <view class="list-bg list-group-row">
        <view class="list-title">订单信息</view>
        <CellAssembly
          :cell-data.sync="curOrderDetailData"
          :cell-column="cellColumn"
          @handelCellMethod="handelCellMethod"
        />
      </view>
      <view class="list-bg list-group-row">
        <view class="list-title">
          可用额度
          <view class="number">{{ creditLines ? '¥ ' + creditLines : '--' }}</view>
        </view>
        <view v-if="creditLines<curOrderDetailData.billAmount" class="error-tips">可用额度不足，请联系销售</view>
      </view>
      <view v-if="curOrderDetailData.customerReceiverTypeId!=0" class="tel-sale-bottom">
        <button
          :type="'default'"
          class="tel-sale-btn"
          :plain="true"
          @click="callPhoneFn"
        >
          <icon class="tel-icon" />
          {{ curOrderDetailData.customerReceiverTypeId == 1 ? '联系销售' : '联系客服' }}
        </button>
      </view>
      <view class="sticky-bottom">
        <!--   #ifdef MP-WEIXIN     -->
        <button
          v-if="false"
          plain="true"
          open-type="share"
          class="share"
        />
        <!--   #endif     -->
        合计：<text class="price">¥ {{ curOrderDetailData.showProductPrice && curOrderDetailData.showProductPrice == 1 ? curOrderDetailData.billAmount : '*.*' }}</text>
        <!--    1订单审核状态：已保存，非保存状态，不显示该按钮   curOrderDetailData.auditStatus==0
                2订单主状态：待确认，非待确认的不显示订单确认按钮  curOrderDetailData.orderStatus==10
                3销售订单的下单账号：与当前登录账号一致，不一致的，不显示该按钮  curOrderDetailData.xdAccount==vuex_accountInfo.loginAccount
                4销售订单的结算方式：为账期支付，非账期支付的不显示该按钮  curOrderDetailData.settleType==1201
                5单据日期：等于系统当前日期或当前日期+1时展示，不满足条件时不显示该按钮 (curOrderDetailData.billDate == curDate || curOrderDetailData.billDate == curDate+1)
                6信用额度可用余额>=订单金额额度不足的，【订单确认】按钮置灰，并显示提醒【账期余额不足，请联系销售】    -->
        <button
          v-if="(curOrderDetailData.auditStatus==0 && curOrderDetailData.orderStatus==10 && (!vuex_loginStatus || (vuex_loginStatus && curOrderDetailData.xdAccount==vuex_accountInfo.loginAccount)) && curOrderDetailData.settleType==1201 && (curOrderDetailData.billDate == curDate || curOrderDetailData.billDate == setFormatDate(curDate)))"
          class="sticky-btn btn-orange"
          :class="(editorStatus || creditLines<curOrderDetailData.billAmount || isClickPayBtn) ? 'disabled-btn' : ''"
          :type="'default'"
          :plain="true"
          :disabled="editorStatus || creditLines<curOrderDetailData.billAmount || isClickPayBtn"
          @click="$u.throttle(confirmOrderCheckFn, 4000)"
        >
          订单确认
        </button>
      </view>
    </view>
  </basePage>
</template>

<script>
import basePage from '@/components/base-page';
import OrderProductItem from '@/components/order-product-list/order-product-item'
import AddressBar from '@/components/addressBar/address-bar'
import CellAssembly from '@/payments/cell-assembly';
import {
  goodseDitor,
  confirmOrderCheck,
  orderComfirm
} from '@/api/payment'
import {
  queryCreditLinesFn,
  getSystemTime,
  formatDate,
  checkMemeberStatusFn
} from '@/common/common'
import {
  prePayMethod,
  payMethod
} from '@/payments/payMethod'
export default {
  name: 'OrderConfirm',
  components: {
    basePage,
    OrderProductItem,
    AddressBar,
    CellAssembly,
  },
  props: {
    orderDetailData: {
      type: Object,
      default: null
    },
    orderProductList: {
      type: Array,
      default: null
    },
    totalRecord: {
      type: Number,
      default: 0
    },
    showWarehouseLabel: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      editorStatus: false,
      creditLines: '', // 可用额度
      cellColumn: [
        {
          label: '客户',
          fields: ['customerCode', 'customerName'],
          separator: ' '
        },
        {
          label: '订单号',
          fields: ['orderNo'],
          btn: [
            {
              btnName: '复制',
              methodName: 'copyFn'
            }
          ]
        },
        {
          label: '支付方式',
          fields: ['settleTypeName']
        },
        {
          label: '配送方式',
          fields: ['sentTypeName', 'mayArrivedEnd'],
          separator: ' '
        },
        {
          label: '备注',
          fields: ['splitJoinRemark']
        }
      ],
      curOrderProductList: [],
      curDate: '',
      isClickPayBtn: false, // 防止重复点击支付按钮重复支付，4秒后重置状态
    }
  },
  computed: {
    curOrderDetailData() {
      return this.orderDetailData
    },
  },
  watch: {
    orderProductList: {
      handler(newVal, oldVal) {
        this.$nextTick(() => {
          this.curOrderProductList = newVal
        })
      },
      deep: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.curOrderProductList = this.orderProductList
    })
    this.initPageFn()
  },
  methods: {
    prePayMethod,
    payMethod,
    initPageFn() {
      this.queryCreditLinesFn()
      this.getAccountTimeFn()
    },
    /*未登录跳转登录*/
    returnLoginFn() {
      const branchData = JSON.stringify({
        branchId: this.curOrderDetailData.branchId,
        branchName: this.curOrderDetailData.branchName,
        settleType: this.curOrderDetailData.settleType,
      })
      const callbackUrl = `/payments/payment/payment`
      const urlParams = JSON.stringify({ orderNo: this.curOrderDetailData.orderNo, pageSource: 'local' })
      uni.redirectTo({
        url: `/login/login/codeLogin?type=confirm&callbackUrl=${callbackUrl}&urlParams=${urlParams}&registParams=${branchData}`
      })
    },
    /*获取时间*/
    async getAccountTimeFn() {
      const time = await getSystemTime()
      this.curDate = formatDate(new Date(time), 'yyyy-mm-dd')
    },
    setFormatDate(time) {
      const orderNextTime = formatDate(new Date(new Date(time).getTime() + (24 * 60 * 60 * 1000)), 'yyyy-mm-dd')
      return orderNextTime
    },
    /*获取可用额度*/
    async queryCreditLinesFn() {
      const params = {
        'customerNumber': this.curOrderDetailData.customerCode, //todo 修改动态number '11.02.16729'
      }
      const creditLinesData = await queryCreditLinesFn(params)
      this.creditLines = creditLinesData[0].internal_credit_data.internal_credit_avail
    },
    /*编辑完成*/
    completeFn() {
      if (this.curOrderProductList.length == 1 && this.curOrderProductList[0].buyyerCount == 0) {
        this.$u.toast('该订单仅含一条商品，不支持修改数量为0，请联系销售修改')
        return
      }
      const editProductList = []
      this.curOrderProductList.forEach((item) => {
        editProductList.push({
          'newBuyyerCount': item.buyyerCount,
          'oldBuyyerCount': item.oldBuyyerCount,
          'productCode': item.productCode,
          'productId': item.productId
        })
      })
      const params = {
        'editProductList': editProductList,
        'orderNo': this.curOrderDetailData.orderNo,
        'memberId': this.vuex_accountInfo.memberId
      }
      goodseDitor(params).then((res) => {
        if (res.errorCode == 0) {
          this.$u.toast('操作成功')
          this.$emit('refreshPage')
          this.queryCreditLinesFn()
          this.getAccountTimeFn()
          this.editorStatus = !this.editorStatus
        } else if (res.errorCode == 1 && res.data == 1) {
          this.$u.toast(res.msg)
          this.$emit('refreshPage')
          this.queryCreditLinesFn()
          this.getAccountTimeFn()
        } else {
          this.$u.toast(res.msg)
        }
      })
    },
    async editFn() {
      if (this.vuex_loginStatus && this.vuex_accountInfo && this.vuex_accountInfo.loginAccount) {
        /*判断当前账号是否是有效账号*/
        const memeberStatus = await checkMemeberStatusFn({ loginAccount: this.vuex_accountInfo.loginAccount })
        if (!memeberStatus) {
          this.returnLoginFn()
          return
        }
        this.editorStatus = !this.editorStatus
      } else {
        this.returnLoginFn()
      }
    },
    /*取消编辑*/
    cancelEditFn() {
      this.$emit('refreshPage')
      this.queryCreditLinesFn()
      this.getAccountTimeFn()
      this.editorStatus = !this.editorStatus
    },
    /*分享*/
    onShareAppMessage() {
      const promise = new Promise(resolve => {
        setTimeout(() => {
          resolve({
            title: '鑫方盛工业品'
          })
        }, 2000)
      })
      return {
        title: '鑫方盛工业品',
        path: 'payments/payment/payment?orderNo=' + this.curOrderDetailData.orderNo + '&settleType=1201&pageSource=local',
        promise
      }
    },
    handelCellMethod(methodName, val) {
      this[methodName](val)
    },
    copyFn(val) {
      uni.setClipboardData({
        data: val,
        success: function(res) {
          uni.getClipboardData({
            success: function(res) {
              uni.showToast({
                title: '已复制到剪贴板'
              });
            }
          });
        }
      })
    },
    /*拼装确认参数*/
    makeConfirmOrderParamsFn() {
      const {
        orderNo,
        billAmount,
      } = this.curOrderDetailData
      const {
        loginAccount,
        memberId,
      } = this.vuex_accountInfo
      const params = {
        'orderNo': orderNo,
        'billAmount': billAmount, //单据金额
        'productCount': this.totalRecord, //商品条目数
        'operatorId': memberId,
        'operatorName': loginAccount,
      }
      return params
    },
    /*确认订单前校验单据*/
    async confirmOrderCheckFn() {
      if (this.isClickPayBtn) {
        return
      }
      this.isClickPayBtn = true
      setTimeout(() => {
        this.isClickPayBtn = false
      }, 4000)
      if (this.vuex_loginStatus && this.vuex_accountInfo && this.vuex_accountInfo.loginAccount) {
        /*判断当前账号是否是有效账号*/
        const memeberStatus = await checkMemeberStatusFn({ loginAccount: this.vuex_accountInfo.loginAccount })
        if (!memeberStatus) {
          this.returnLoginFn()
          return
        }
        /*订单支付锁定状态为”否(0)“时，点击【订单确认】/【去支付】时，提醒”您的订单客服正在修改中，请稍后再试“*/
        if (this.curOrderDetailData.lockedStatus == 0) {
          this.$u.toast('您的订单客服正在修改中，请稍后再试')
          return
        }
        const params = this.makeConfirmOrderParamsFn()
        confirmOrderCheck(params).then((res) => {
          if (res.errorCode == 0) {
            this.paymentFn()
          } else {
            this.$u.toast(res.msg ? res.msg : '单据异常')
          }
        })
      } else {
        this.returnLoginFn()
      }
    },
    orderComfirmFn() {
      const {
        orderNo,
        orderType,
        signWay,
        billAmount
      } = this.curOrderDetailData
      const params = this.makeConfirmOrderParamsFn()
      orderComfirm(params).then((res) => {
        if (res.errorCode == 0) {
          /*orderType 19654,"店面自提"、19651,"无货自提"、19655,"配送客户自提"
          * signWay (0, "未签收"),(1, "电子签收"),(2, "纸质签收"),(3, "提货码核销"),(4, "收银台审核触发已签收"),(5, "订单对账"),(6, "超时自动确认收货"),(7, "正票签收触发已签收"),(8, "客户自主确认收货"),(9, "正向销售订单整单逆向触发签收"),(10, "提货码提货销售订单整单换货触发签收");
          * 提货码核销生成提货码，其他不生成*/
          this.$nextTick(() => {
            if ((orderType == 19654 || orderType == 19651 || orderType == 19655) && signWay == 3) {
              uni.redirectTo({
                url: '/payments/paymentSuccess/index?amount=' + billAmount + '&orderno=' + orderNo
              });
            } else {
              uni.redirectTo({
                url: '/payments/confirmResult/index?type=success&orderNo=' + orderNo + '&phoneNumber=' + this.curOrderDetailData.departmentPhone
              });
            }
          })
        } else if (res.errorCode == 1) {
          uni.redirectTo({
            url: '/payments/confirmResult/index?type=error&orderNo=' + orderNo + '&phoneNumber=' + this.curOrderDetailData.departmentPhone + '&msg=' + res.msg
          });
        } else {
          this.$u.toast(res.msg || '确认失败')
        }
      })
    },
    async prePayFn() {
      const {
        orderNo: orderPayNo,
        customerCode,
        branchId: belongGroupId,
        sendDepartmentId,
        billAmount: totalOrderAmount
      } = this.curOrderDetailData
      const prePayParams = { platform: 'MD', orderId: orderPayNo, totalAmount: totalOrderAmount, customerCode, sendDepartmentId, belongGroupId }
      this.prePayInfo = await this.prePayMethod(prePayParams).catch((e) => {
        this.$u.toast(e.message)
      })
    },
    /*确认订单*/
    async paymentFn() {
      await this.prePayFn()
      if (!this.prePayInfo) {
        return
      }
      const payWayUnifyCode = 'AccountPay' // 支付方式统一编码，用于不区分支付渠道，由服务端根据规则选择支付渠道 WechatPay=微信支付 AliPay=支付宝 EPay=网银支付 QuickPay=快捷 AccountPay=账期 PingAnPay=平安支付
      const {
        orderNo,
        departmentPhone
      } = this.curOrderDetailData
      const {
        needPayAmount,
        payId,
        totalAmount,
      } = this.prePayInfo
      const payParams = {
        platform: 'MD',
        payWayUnifyCode,
        payId,
        payableAmount: needPayAmount,
        payInfoTotalAmount: totalAmount
      }
      // 支付成功回调函数
      const successFn = () => {
        this.orderComfirmFn()
      }
      // 支付失败回调函数
      const failFn = (res) => {
        const {
          code,
          msg,
        } = res
        if (code == 90000) {
          this.$u.toast(msg || '支付失败')
        } else {
          uni.redirectTo({
            url: '/payments/confirmResult/index?type=error&orderNo=' + orderNo + '&phoneNumber=' + departmentPhone + '&msg=' + msg
          })
        }
      }
      await this.payMethod(payParams, successFn, failFn)
    },
    /*联系销售*/
    callPhoneFn() {
      /*customerReceiverTypeId-客户对接人类型id( 1是 联系销售、2是 联系客服)*/
      let phoneNumber = ''
      if (this.curOrderDetailData.customerReceiverTypeId == 1) {
        phoneNumber = this.curOrderDetailData.departmentPhone
      } else if (this.curOrderDetailData.customerReceiverTypeId == 2) {
        phoneNumber = this.curOrderDetailData.rolePhone
      }
      uni.makePhoneCall({
        phoneNumber: phoneNumber,
        fail: (res) => {
          this.$u.toast('拨打失败')
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.order-payment-con{
  .list-sku{
    position: relative;
    .company{
      padding:20rpx 0 30rpx 64rpx;
      background:url("../../static/image/shop.png") no-repeat 24rpx 20rpx/30rpx auto;
      height: 30rpx;
    }
    .editor-box{
      position: absolute;
      text-align: right;
      color:$uni-orange;
      right:20rpx;
      top:20rpx;
    }
  }
  padding-top:10rpx;
  padding-bottom:238rpx;
  .tel-sale-bottom {
    position: fixed;
    bottom:170rpx;
    height: 68rpx;
    width: 100%;
    .tel-sale-btn{
      width:710rpx;
      height:68rpx;
      margin: 0 auto;
      line-height: 68rpx;
      border-radius:8px;
      border: 0!important;
      font-size: 28rpx;
      color:#fff!important;
      background: #474747;
    }
    .tel-icon{
      background:url("../../static/image/tel-sale.png") no-repeat 0 0/100%;
      width: 24rpx;
      height: 26rpx;
      position: relative;
      margin-right:6rpx;
      top:2rpx;
    }
  }
  .error-tips{
    float: right;
    padding: 10rpx 0;
    color: $uni-color-error;
  }
  .share{
    background:url("../../static/image/share.png") no-repeat 0 0/40rpx auto;
    width: 40rpx;
    height: 40rpx;
    float: left;
    margin: 32rpx 0 0 24rpx;
    border: #fff;
  }
  .sticky-btn{
    float: right;
    margin:8rpx 0 0 58rpx;
  }
  .disabled-btn{
    background: $uni-text-color-disable;
  }
  .font-size-color {
    margin-right: 10rpx;
  }
}
</style>
